package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //查询今日佳人（查询推荐用户中评分最高的一项）
    public RecommendUser queryWithMaxScore(Long toUserId) {
        //1、创建Criteria对象，指定查询条件（toUserId）
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2、创建Query对象
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score")))
                .limit(1);
        //3、调用mongoTemplate查询数据（一项！）
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    //分页查询
    public PageResult queryRecommendUserList(Long toUserId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        Query query = Query.query(criteria);
        //1、查询总数
        long count = mongoTemplate.count(query, RecommendUser.class);
        //2、查询分页的数据列表
        query.with(Sort.by(Sort.Order.desc("score"))).skip((page - 1) * pagesize).limit(pagesize); //设置分页的参数
        List<RecommendUser> list = mongoTemplate.find(query, RecommendUser.class);
        //3、封装PageResult
        return new PageResult(page,pagesize,count,list);
    }

    @Override
    public RecommendUser queryByUserId(Long userId, Long toUserId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("toUserId").is(toUserId);
        Query query = Query.query(criteria);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setToUserId(toUserId);
            recommendUser.setScore(95d);
        }
        return recommendUser;
    }
}
